//
//  DiscoverHouseholdListViewController.m
//  HJB
//
//  Created by jiezsoft.com on 14-10-10.
//  Copyright (c) 2014年 jiezsoft.com. All rights reserved.
//

#import "DiscoverBusinessListViewController.h"
#import "DiscoverBusinessDetailViewController.h"
#import "HAODEsingleton.h"
#import "UIViewExt.h"
#import "CycleScrollViews.h"
#import "HttpRequest.h"
#import "JSONKit.h"
#import "UIButton+WebCache.h"
#import "HouseholdListCell.h"
//#import "EventDetailsViewController.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"

@interface DiscoverBusinessListViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (strong, nonatomic) NSString *areaValue;
@property (strong, nonatomic) NSString*cityValue;


@end

@implementation DiscoverBusinessListViewController

{
    UISearchBar *search;
    HAODEsingleton* commdity;
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*fid;
    NSMutableArray*title;
    NSMutableArray*content;
    NSMutableArray*imageUrl;
    NSMutableArray*author;
    NSMutableArray*pubTime;
    NSMutableArray*collectCount;
    NSMutableArray*commentCount;
    NSMutableArray*LinkType;
    NSMutableArray*LinkCode;
    NSMutableArray*ImageUrl;
    NSString*TotalCount;
    CycleScrollViews *mainScorllView;
    NSString *result;
    float lastContentOffset;
    int pageNumber;
}
@synthesize alt = alt;


- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden = NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
}


- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    
    [self add];
    
    [self addheader];
    [self addFooter];
    
}
-(void)add{
    self.sat=nil;
    
    pubTime= [[NSMutableArray alloc] init];
    author= [[NSMutableArray alloc] init];
    imageUrl= [[NSMutableArray alloc] init];
    content= [[NSMutableArray alloc] init];
    title= [[NSMutableArray alloc] init];
    fid= [[NSMutableArray alloc] init];
    LinkType= [[NSMutableArray alloc] init];
    LinkCode= [[NSMutableArray alloc] init];
    ImageUrl= [[NSMutableArray alloc] init];
    
    self.title=@"生意经";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    _table.delegate=self;
    _table.dataSource=self;
    _table.separatorStyle=UITableViewCellSeparatorStyleNone;
    commdity=[HAODEsingleton shared];
    
    
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"StarIndex"];
    [param setValue:@"20" forKey:@"PageSize"];
    
    
    NSLog(@"====%@",param);
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"/Discover/Business/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) { NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    
                    [author addObject:[dicc valueForKey:@"author"]];
                    [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                    [content addObject:[dicc valueForKey:@"content"]];
                    [fid addObject:[dicc valueForKey:@"fid"]];
                    [title addObject:[dicc valueForKey:@"title"]];
                    
                    NSString* string =  [dicc valueForKey:@"pubTime"];
                    NSLog(@"-------------%@",string);
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                    NSDate *destDate= [dateFormatter dateFromString:string];
                    
                    NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                    timeInterval = -timeInterval;
                    
                    
                    
                    long temp = 0;
                    
                    if (timeInterval < 60) {
                        result = [NSString stringWithFormat:@"刚刚"];
                    }
                    else if((temp = timeInterval/60) <60){
                        result = [NSString stringWithFormat:@"%ld分前",temp];
                    }
                    
                    else if((temp = temp/60) <24){
                        result = [NSString stringWithFormat:@"%ld小时前",temp];
                    }
                    
                    else if((temp = temp/24) <30){
                        result = [NSString stringWithFormat:@"%ld天前",temp];
                    }
                    
                    else if((temp = temp/30) <12){
                        result = [NSString stringWithFormat:@"%ld月前",temp];
                    }
                    else{
                        temp = temp/12;
                        result = [NSString stringWithFormat:@"%ld年前",temp];
                    }
                    
                    
                    [pubTime addObject:result];
                    
                    
                }
                
                if (arrr.count>0) {
                    [self _AutoScrollView];
                    
                }
                if (arrr.count>1) {
                    [author removeObjectAtIndex:0];
                    [ImageUrl removeObjectAtIndex:0];
                    [content removeObjectAtIndex:0];
                    [fid removeObjectAtIndex:0];
                    [title removeObjectAtIndex:0];
                    [pubTime removeObjectAtIndex:0];
                    
                }

                [_table reloadData];
                
                
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                // [Global showTextHud:requestResultStr view:self.view];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
    
    
    
    
    
    
    
    
}

//下拉刷新
- (void)addheader
{
    
    
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView =_table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        
        [self add];
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
}



//上拉刷新
- (void)addFooter
{
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = _table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        if (TotalCount.intValue/30>=pageNumber) {
            pageNumber++;
            
            NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
            NSString* tokenId = [user1 objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:tokenId forKey:@"tokenId"];
            
            [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            
            [params setValue:@"20" forKey:@"pageSize"];
            
            
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            
            
            [HttpRequest requestData:@"/Discover/Business/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    NSLog(@"====%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        NSMutableArray* arrr=[[NSMutableArray alloc]init];
                        
                        arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                        for (NSDictionary* dicc in arrr )
                        {
                            
                            [author addObject:[dicc valueForKey:@"author"]];
                            [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                            [content addObject:[dicc valueForKey:@"content"]];
                            [fid addObject:[dicc valueForKey:@"fid"]];
                            [title addObject:[dicc valueForKey:@"title"]];
                            
                            NSString* string =  [dicc valueForKey:@"pubTime"];
                            NSLog(@"-------------%@",string);
                            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                            [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                            NSDate *destDate= [dateFormatter dateFromString:string];
                            
                            NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                            timeInterval = -timeInterval;
                            
                            
                            
                            long temp = 0;
                            
                            if (timeInterval < 60) {
                                result = [NSString stringWithFormat:@"刚刚"];
                            }
                            else if((temp = timeInterval/60) <60){
                                result = [NSString stringWithFormat:@"%ld分前",temp];
                            }
                            
                            else if((temp = temp/60) <24){
                                result = [NSString stringWithFormat:@"%ld小时前",temp];
                            }
                            
                            else if((temp = temp/24) <30){
                                result = [NSString stringWithFormat:@"%ld天前",temp];
                            }
                            
                            else if((temp = temp/30) <12){
                                result = [NSString stringWithFormat:@"%ld月前",temp];
                            }
                            else{
                                temp = temp/12;
                                result = [NSString stringWithFormat:@"%ld年前",temp];
                            }
                            
                            
                            [pubTime addObject:result];
                            
                            
                        }
                        //                        if (arrr.count>0) {
                        //                            [self _AutoScrollView];
                        //
                        //                        }
                        //
                        //                        if (arrr.count>1) {
                        //                            [author removeObjectAtIndex:0];
                        //                            [ImageUrl removeObjectAtIndex:0];
                        //                            [content removeObjectAtIndex:0];
                        //                            [fid removeObjectAtIndex:0];
                        //                            [title removeObjectAtIndex:0];
                        //                            [pubTime removeObjectAtIndex:0];
                        //
                        //                        }
                        
                        [_table reloadData];
                        
                        
                        
                        
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        // [Global showTextHud:requestResultStr view:self.view];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
        }else{
            
            NSString *requestResultStr=@"没有更多数据了！";
            // [Global showTextHud:requestResultStr view:self.view];
            [Global showTextHudSub:requestResultStr view:self.view];
            
            
        }
        
        
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [_table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [title count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    HouseholdListCell* cell = (HouseholdListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"HouseholdListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    [cell.imageUrl.layer setCornerRadius:4.0];
    [cell.imageUrl.layer setBorderWidth:0.3];
    [cell.imageUrl.layer setMasksToBounds:YES];
    CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref2 = CGColorCreate(colorSpace2,(CGFloat[]){ 0, 0, 0, 0.3 });
    [cell.imageUrl.layer setBorderColor:colorref2];//边框颜色

    [cell.imageUrl setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:indexPath.row]]placeholderImage:[UIImage imageNamed:@""]];
    
    cell.title.text =[NSString stringWithFormat:@"%@",  [title objectAtIndex:indexPath.row]];
    
    
    cell.time.text =[NSString stringWithFormat:@"%@",  [pubTime objectAtIndex:indexPath.row]];
    cell.author.text =[NSString stringWithFormat:@"%@",  [author objectAtIndex:indexPath.row]];
    
    
    
    
    if (title.count !=indexPath.row+1) {
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(15, 90-0.35, ScreenWidth-30, 0.35)];
        lineLabel1.backgroundColor=qianhuicolor;
        [cell.contentView addSubview:lineLabel1];
        
    }
    
    if (title.count ==indexPath.row+1) {
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(0, 90-0.35, ScreenWidth, 0.35)];
        lineLabel1.backgroundColor=qianhuicolor;
        [cell.contentView addSubview:lineLabel1];
        
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  90;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    commdity.ImageUrl=ImageUrl[indexPath.row];
    commdity.reqId=fid[indexPath.row];
    commdity.content=content[indexPath.row];
    commdity.title=title[indexPath.row];
    DiscoverBusinessDetailViewController *detailViewController = [[DiscoverBusinessDetailViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
    //
    
    
    
    
}




- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
//轮播视图
- (void )_AutoScrollView {
    
    commdity.ImageUrl=[ImageUrl objectAtIndex:0];
    commdity.content=[content objectAtIndex:0];
    commdity.title=[title objectAtIndex:0];
 
    UIButton* button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 210)];
    [button setTitle:[fid objectAtIndex:0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    
    button.contentMode = UIViewContentModeScaleAspectFill;
    [button setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@""]];
    
    [button  addTarget:self action:@selector(Btn:) forControlEvents:UIControlEventTouchUpInside];
    UILabel*label1=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    label1.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    label1.backgroundColor=[UIColor blackColor];
    label1.alpha=0.5;
    label1.font=[UIFont systemFontOfSize:16];
    [button addSubview:label1];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    label.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    label.textColor=[UIColor whiteColor];
    label.font=[UIFont systemFontOfSize:16];
    [button addSubview:label];
    
    _table. tableHeaderView=button;
    
}


-(void)Btn:(UIButton*)sender{
    
    commdity.reqId=sender.titleLabel.text;
       //
    //    commdity.ConditDesp=[ConditDesp objectAtIndex:indexPath.row];
    //    commdity.LastDate1= [LastDate objectAtIndex:indexPath.row];
    DiscoverBusinessDetailViewController *detailViewController = [[DiscoverBusinessDetailViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
    //
    
    
    
}

-(void)jiazai1{
    //    [jiazai removeFromSuperview];
    [self _AutoScrollView];
    
}


@end
